Imports Microsoft.VisualBasic

Public Class MaxIDManager
    Private _tableName As String

    Public Sub New(ByVal tableName As String)
        Me._tableName = tableName
    End Sub

    Public Function GetCurrent() As Integer
        Dim dat As New clsData
        Dim sql As New StringBuilder
        Dim params As New List(Of SqlParameter)

        sql.AppendFormat("SELECT MaxID FROM MaxID WHERE TableName = @TableName")

        params.Add(New SqlParameter("TableName", Me._tableName))

        Dim value As Object = dat.GetSingleData(sql.ToString(), params.ToArray)

        If value Is Nothing Then
            Return 0
        Else
            Return Convert.ToInt32(value)
        End If
    End Function

    Public Function Increment() As Integer
        Dim original As Integer = GetCurrent()

        Dim dat As New clsData
        Dim sql As New StringBuilder
        Dim params As New List(Of SqlParameter)

        If original = 0 Then
            sql.AppendFormat("DELETE MaxID WHERE TableName = @TableName ")
            sql.AppendFormat("INSERT MaxID (TableName, MaxID) SELECT @TableName, @MaxID ")
        Else
            sql.AppendFormat("UPDATE MaxID SET MaxID = @MaxID WHERE TableName = @TableName")
        End If

        Dim newvalue As Integer = original + 1

        params.Add(New SqlParameter("TableName", Me._tableName))
        params.Add(New SqlParameter("MaxID", newvalue))

        dat.AccData(sql.ToString, params.ToArray)

        Return newvalue
    End Function

    'ADD By Penny 20100909
    'Public Sub Update(ByVal YearMon As String)
    '    Dim original As Integer = GetCurrent()

    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder
    '    Dim params As New List(Of SqlParameter)

    '    If original = 0 Then
    '        sql.AppendFormat("DELETE MaxID WHERE TableName = @TableName ")
    '        sql.AppendFormat("INSERT MaxID (TableName, MaxID) SELECT @TableName, @MaxID ")
    '    Else
    '        sql.AppendFormat("UPDATE MaxID SET MaxID = @MaxID WHERE TableName = @TableName")
    '    End If

    '    params.Add(New SqlParameter("TableName", Me._tableName))
    '    params.Add(New SqlParameter("MaxID", YearMon))

    '    dat.AccData(sql.ToString, params.ToArray)

    'End Sub
End Class
